package ixRedis

import "github.com/garyburd/redigo/redis"

// LPush 从左侧推入列表
func (c *Client) LPush(key string, values ...interface{}) (int64, error) {
	if len(values) == 0 {
		return 0, nil
	}

	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	args := make([]interface{}, len(values)+1)
	args[0] = fullKey
	for i, value := range values {
		args[i+1] = value
	}

	return redis.Int64(conn.Do("LPUSH", args...))
}

// RPush 从右侧推入列表
func (c *Client) RPush(key string, values ...interface{}) (int64, error) {
	if len(values) == 0 {
		return 0, nil
	}

	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	args := make([]interface{}, len(values)+1)
	args[0] = fullKey
	for i, value := range values {
		args[i+1] = value
	}

	return redis.Int64(conn.Do("RPUSH", args...))
}

// LPop 从左侧弹出列表元素
func (c *Client) LPop(key string) (string, error) {
	conn, err := c.getConn()
	if err != nil {
		return "", err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	reply, err := redis.String(conn.Do("LPOP", fullKey))
	if err == redis.ErrNil {
		return "", nil
	}
	return reply, err
}

// RPop 从右侧弹出列表元素
func (c *Client) RPop(key string) (string, error) {
	conn, err := c.getConn()
	if err != nil {
		return "", err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	reply, err := redis.String(conn.Do("RPOP", fullKey))
	if err == redis.ErrNil {
		return "", nil
	}
	return reply, err
}

// LLen 获取列表长度
func (c *Client) LLen(key string) (int64, error) {
	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	return redis.Int64(conn.Do("LLEN", fullKey))
}

// LRange 获取列表范围
func (c *Client) LRange(key string, start, stop int64) ([]string, error) {
	conn, err := c.getConn()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	return redis.Strings(conn.Do("LRANGE", fullKey, start, stop))
}
